<?php

namespace app\admin\controller;

use app\api\service\HuaWeiOBS;
use app\common\controller\Api;
use app\common\controller\Backend;
use app\common\library\Auth;
use app\common\model\Attachment;
use http\Env\Request;
use think\Env;
use think\File;
use think\Model;
use function GuzzleHttp\Promise\all;

/**
 * 上传文件
 * Class UploadFile
 * @package app\admin\controller
 */
class UploadFile extends Backend
{

    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
    }

    //上传文件到OBS
    public function uploadOBS(HuaWeiOBS $huaWeiOBS){
        set_time_limit(0); // 0 表示无限制，允许脚本执行的时间无限长(秒)
//        $file = $this->request->file('file');//上传的文件
        $file = $_FILES['file'];
//        if ($file['size'] > 10250000){
//            $this->error('文件大小不能超过10MB');
//        }

        //将文件保存到华为云OBS中
        $putObject = $huaWeiOBS->putObject($file);
        if ($putObject['code'] != 200){
            $this->error('上传失败');
        }

        $imageInfo = getimagesize($file['tmp_name']);
        $fileInfo = [
            'imagewidth'  => $imageInfo[0] ?? '',
            'imageheight' => $imageInfo[1] ?? '',
            'imagetype'   => $imageInfo[2] ?? '',

            'mimetype'   => $file['type'],
            'filesize'   => $file['size'],//字节
        ];

        $sha1 =  hash_file('sha1', $file['tmp_name']);

        $category = $this->request->post('category','');
        $category = array_key_exists($category, config('site.attachmentcategory') ?? []) ? $category : '';
        $auth = Auth::instance();
        $params = array(
            'admin_id'    => (int)session('admin.id'),
            'user_id'     => (int)$auth->id,
            //'filename'    => mb_substr(htmlspecialchars(strip_tags($putObject['file_name'])), 0, 100),
            'filename'    => $file['name'],
            'category'    => $category,
            'filesize'    => $fileInfo['filesize'],
            'imagewidth'  => $fileInfo['imagewidth'],
            'imageheight' => $fileInfo['imageheight'],
            'imagetype'   => $fileInfo['imagetype'],
            'imageframes' => 0,
            'mimetype'    => $fileInfo['mimetype'],
            'url'         => $putObject['path'],
            'uploadtime'  => time(),
            'storage'     => 'obs',
            'sha1'        => $sha1,
            'extparam'    => '',
        );
        //把上传的文件保存到附件表中
        $attachment = new Attachment();
        $attachment->data(array_filter($params));
        $attachment->save();

        \think\Hook::listen("upload_after", $attachment);

        return [
            'code' => 1,
            'msg' => '上传成功',
            'data' => [
                'filename' => $file['name'],//文件原名称
                'url' => $putObject['path'],//相对路径
                'fullurl' => $putObject['url'],//绝对路径
            ],
            'url' => '',
            'wait' => 3,
        ];
    }

    //获取分段上传初始化参数-华为OBS
    public function initiateMultipartUpload(){
        $file_name = $this->request->param('file_name');
        $file_name = time() . rand(1111, 9999) . '.' . pathinfo($file_name, PATHINFO_EXTENSION);
        $path = 'uploads/' . date('Ymd') . '/' . $file_name;
        $huaWeiOBS = new HuaWeiOBS();
        $data = $huaWeiOBS->initiateMultipartUpload($path);
        $res = [
            'code' => 1,
            'msg' => '上传成功',
            'data'=>[
                'path'=>$path,
                'upload_id'=>$data['UploadId'],
            ]
        ];
        return $res;
    }

    //开始上传分片-华为OBS
    public function uploadPart(){
        $file = $_FILES['chunk'];
        $source_file = $file['tmp_name'];//待上传对象的源文件路径
        $upload_id = $this->request->param('upload_id');
        $path = $this->request->param('path');
        $part_number = $this->request->param('part_number');//设置分段号，范围是1~10000

        $huaWeiOBS = new HuaWeiOBS();
        $data = $huaWeiOBS->uploadPart($source_file,$path,$upload_id,$part_number);
        $res = [
            'code' => 1,
            'msg' => '上传成功',
            'data'=>[
                'PartNumber'=>$part_number,
                'ETag'=>$data['ETag'],
            ]
        ];
        return $res;
    }

    //合并上传文件-华为OBS
    public function completeMultipartUpload(){
        $file_name = $this->request->param('file_name');//文件原名称
        $upload_id = $this->request->param('upload_id');
        $parts = $_POST['parts'];
        $path = $this->request->param('path');

        $huaWeiOBS = new HuaWeiOBS();
        $data = $huaWeiOBS->completeMultipartUpload($upload_id,$parts,$path);
        $res = [
            'code' => 0,
            'msg' => '上传合并失败',
        ];
        if ($data['code'] == 200){
            $res = [
                'code' => 1,
                'msg' => '上传成功',
                'data'=>[
                    'filename' => $file_name,//文件原名称
                    'url' => $data['path'],//相对路径
                    'fullurl' => $data['url'],//绝对路径
                ]
            ];
        }

        $auth = Auth::instance();
        $params = array(
            'url'         => $data['path'],
            'filename'    => $file_name,
            'storage'     => 'obs',
            'admin_id'    => (int)session('admin.id'),
            'user_id'     => (int)$auth->id,
            'createtime'  => time(),
            'uploadtime'  => time(),
            'extparam'    => '',
        );
        //把上传的文件保存到附件表中
        $attachment = new Attachment();
        $attachment->data(array_filter($params));
        $attachment->save();

        \think\Hook::listen("upload_after", $attachment);

        return $res;
    }


    //// 使用 CURL 获取远程文件大小
    public function getFileSize($url){
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_NOBODY, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        $data = curl_exec($ch);
        $file_size = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
        curl_close($ch);
        return $file_size;
    }

}
